package com.supercube.sport.yoga.controller;

import com.github.pagehelper.PageInfo;
import com.supercube.common.utils.ShiroUtils;
import com.supercube.sport.yoga.dao.CorrelationVenueMapper;
import com.supercube.sport.yoga.domain.CorrelationVenueDTO;
import com.supercube.sport.yoga.domain.UserCorrelationVenue;
import com.supercube.sport.yoga.domain.VenueInfoDTO;
import com.supercube.sport.yoga.service.MemberCardService;
import com.supercube.sport.yoga.service.SiteInfoService;
import com.supercube.sport.yoga.service.VenueInfoService;
import com.supercube.sport.yoga.utils.ResultInfo;
import com.supercube.sport.yoga.utils.UserUtils;
import com.supercube.sport.yoga.vo.SiteInfoVO;
import com.supercube.sport.yoga.vo.VenueInfoVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/venueInfo")
@Api(tags = "场馆管理")
public class VenueInfoController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private VenueInfoService venueInfoService;

    @Autowired
    private SiteInfoService siteInfoService;

    @Autowired
    private MemberCardService memberCardService;

    @Autowired
    private CorrelationVenueMapper correlationVenueMapper;

    /**
     * 保存场馆基本信息
     *
     * @param dto
     * @return
     */
    @ApiOperation(value = "保存场馆基本信息", notes = "保存场馆基本信息")
    @PostMapping("/save")
    public ResultInfo saveVenueInfo(@RequestBody VenueInfoDTO dto) {
        if (ShiroUtils.getUserId() != 1L) {
            return ResultInfo.failed("不是管理员不可操作场馆");
        }
        String id = UUID.randomUUID().toString();
        dto.setId(id);
        venueInfoService.save(dto);
        CorrelationVenueDTO correlationVenueDTO = new CorrelationVenueDTO();
        correlationVenueDTO.setId(UUID.randomUUID().toString());
        correlationVenueDTO.setVenueId(id);
        correlationVenueDTO.setEmpId(1L);
        correlationVenueMapper.insert(correlationVenueDTO);
        return ResultInfo.success("保存成功");
    }

    @ApiOperation(value = "修改场馆基本信息", notes = "修改场馆基本信息")
    @PostMapping("/update")
    public ResultInfo updateVenueInfo(@RequestBody VenueInfoDTO dto) {
        if (ShiroUtils.getUserId() != 1L) {
            return ResultInfo.failed("不是管理员不可操作场馆");
        }
        venueInfoService.update(dto);
        return ResultInfo.success("修改成功");
    }

    @ApiOperation(value = "删除场馆基本信息", notes = "删除场馆基本信息")
    @GetMapping("/delete")
    public ResultInfo deleteVenueInfoById(@RequestParam("id") String id) {
        if (ShiroUtils.getUserId() != 1L) {
            return ResultInfo.failed("不是管理员不可操作场馆");
        }
        // 关联场地校验
        List<SiteInfoVO> siteInfoVOList = siteInfoService.querySiteInfoByVenueId(id, null);
        if (CollectionUtils.isNotEmpty(siteInfoVOList)) {
            return ResultInfo.failed("删除失败，存在关联的场地");
        }

        // TODO 员工可操作场馆
        // TODO 课程所属场馆
        // TODO 会员卡适用场馆
        int countVenues = memberCardService.queryCountCardSupportVenuesByVenuesId(id);
        if (countVenues > 0) {
            return ResultInfo.failed("删除失败，存在关联的会员卡");
        }

        // TODO 会员消费场馆
        // TODO 商品所属场馆
        venueInfoService.deleteVenueInfoById(id);
        return ResultInfo.success("删除成功");
    }

    @ApiOperation(value = "批量删除场馆基本信息", notes = "批量删除场馆基本信息")
    @GetMapping("/batchDeleteVenueInfoByIds")
    public ResultInfo batchDeleteVenueInfoByIds(@RequestParam("ids") String[] ids) {
        if (ShiroUtils.getUserId() != 1L) {
            return ResultInfo.failed("不是管理员不可操作场馆");
        }
        List<String> success = new ArrayList<>();
        for (String id : ids) {
            List<SiteInfoVO> siteInfoVOList = siteInfoService.querySiteInfoByVenueId(id, null);
            if (CollectionUtils.isEmpty(siteInfoVOList)) {
                if (venueInfoService.deleteVenueInfoById(id) > 0) {
                    success.add(id);
                }
            }
        }
        String message = "";
        try {
            message = "删除成功数:" + success.size() + ",删除失败数：" + (ids.length - success.size());
        } catch (Exception e) {
            logger.error("统计有误！" + e);
        }
        return ResultInfo.success("删除完成", message);
    }

    @ApiOperation(value = "查询场馆基本信息详情", notes = "查询场馆基本信息详情")
    @PostMapping("/queryVenueInfoById")
    public ResultInfo queryVenueInfoById(@RequestParam("id") String id) {
        VenueInfoVO vo = venueInfoService.queryVenueInfoById(id);
        return ResultInfo.success(vo);
    }

    @ApiOperation(value = "查询场馆基本信息详情列表", notes = "查询场馆基本信息详情列表")
    @PostMapping("/list")
    public ResultInfo queryVenueInfoList(@RequestBody VenueInfoDTO dto) {
        List<VenueInfoVO> list = null;
        try {
            list = venueInfoService.selectVenueInfoList(BeanUtils.describe(dto));
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        PageInfo<VenueInfoVO> pageInfo = new PageInfo<>(list);
        return ResultInfo.success(pageInfo);
    }


    @ApiOperation(value = "保存员工和场馆关联关系", notes = "保存员工和场馆关联关系")
    @PostMapping("/saveUserCorrelationVenue")
    public ResultInfo saveUserCorrelationVenue(@RequestBody UserCorrelationVenue dto) {
        venueInfoService.saveUserCorrelationVenue(dto);
        return ResultInfo.success("保存成功");
    }

    @ApiOperation(value = "根据登录用户id查询可操作场馆信息列表", notes = "根据登录用户id查询可操作场馆信息列表")
    @PostMapping("/queryVenueInfoListByUserId")
    public ResultInfo queryVenueInfoListByUserId(@RequestParam("userId") String userId) {
        List<VenueInfoDTO> list = venueInfoService.queryVenueInfoListByUserId(userId);
        return ResultInfo.success(list);
    }
}
